package com.hnevc.androiduiclassone8;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.Toast;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

public class JSONActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_json);

        String jsonString="{\"name\":\"tom\",\"password\":\"123\",\"address\":{\"county\":\"中国\",\"city\":\"长沙\"}}";
        String jsonArrayString="[12,23,45,56,678]";

        try {
            JSONArray array=new JSONArray(jsonArrayString);
            for (int i=0;i<array.length();i++){
                int num=array.getInt(i);
                Toast.makeText(this,""+num,Toast.LENGTH_SHORT).show();

            }
        } catch (JSONException e) {
            e.printStackTrace();
        }


        try {
            JSONObject object =new JSONObject(jsonString);
            String name=object.getString("name");
            JSONObject address=object.getJSONObject("address");
            String county=address.getString("county");
            Toast.makeText(this,county,Toast.LENGTH_SHORT).show();

            Toast.makeText(this,name,Toast.LENGTH_SHORT).show();

        } catch (JSONException e) {
            e.printStackTrace();
        }

    }
}
